<?php

namespace Icsoc\IvrBundle\Controller;

use GuzzleHttp\Client;
use Icsoc\CoreBundle\Export\DataType\ArrayType;
use Doctrine\ORM\NoResultException;
use Icsoc\CoreBundle\Controller\BaseController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Icsoc\CoreBundle\Logger\ActionLogger;
use Icsoc\IvrBundle\Form\Type\NodesType;

/**
 * ivr配置相关程序
 * Class IvrController
 * @package Icsoc\IvrBundle\Controller
 */
class IvrController extends BaseController
{
    /** 根节点 */
    const NODE_TYPE_ROOT = 1;
    /** 放音节点 */
    const NODE_TYPE_SOUND = 2;
    /** 按键导航节点 */
    const NODE_TYPE_NAVIGATION = 3;
    const NODE_TYPE_NAVIGATION_KEY = 30;
    /** 转技能组节点 */
    const NODE_TYPE_QUEUE = 5;
    const NODE_TYPE_QUEUE_CHILDREN = 50;
    /** 留言节点 */
    const NODE_TYPE_MESSAGE = 6;
    /** 挂机节点 */
    const NODE_TYPE_HANGUP = 7;
    /** 收键节点 */
    const NODE_TYPE_KEYS = 8;
    const NODE_TYPE_KEYS_CHILDREN = 80;
    /** http接口交互节点 */
    const NODE_TYPE_HTTP = 9;
    const NODE_TYPE_HTTP_CHILDREN = 90;
    /** 来电记忆节点 */
    const NODE_TYPE_CALL_MEMORY = 10;
    const NODE_TYPE_CALL_MEMORY_CHILDREN = 100;
    /** 转电话节点 */
    const NODE_TYPE_PHONE = 11;
    /** 转坐席节点 */
    const NODE_TYPE_AGENT = 12;
    /** 判断节点 */
    const NODE_TYPE_JUDGE = 13;
    const NODE_TYPE_JUDGE_CHILDREN = 130;
    /** 已存在节点类型 */
    const NODE_TYPE_EXISTS = 999;
    /** 转IVR节点 */
    const NODE_TYPE_IVR = 14;

    /** @var array 所有的节点类型 */
    private $nodes = array(
        'System Node' => array(
            self::NODE_TYPE_HANGUP => 'Hangup',
        ),
        'New Nodes' => array(
            self::NODE_TYPE_SOUND => 'Play Sound',
            self::NODE_TYPE_NAVIGATION => 'Navigation',
            self::NODE_TYPE_QUEUE => 'Go To Queue',
            self::NODE_TYPE_MESSAGE => 'Leave Message',
            self::NODE_TYPE_KEYS => 'Receive Keys',
            self::NODE_TYPE_HTTP => 'Http Api',
            self::NODE_TYPE_CALL_MEMORY => 'Call Memory',
            self::NODE_TYPE_PHONE => 'Go To Phone',
            self::NODE_TYPE_AGENT => 'Go To Agent',
            self::NODE_TYPE_JUDGE => 'Judge',
            self::NODE_TYPE_IVR => 'Go To Ivr',
        ),
    );

    /** 语音列表 */
    const SOUND_TYPE_SOUND_LIST = 1;
    /** 数字 */
//    const SOUND_TYPE_NUMBER = 2;
    /** 数字变量 */
    const SOUND_TYPE_NUMBER_VARIABLE = 3;
    /** 数字变量 */
    const SOUND_TYPE_TTS = 4;

    /** @var array 语音类型 */
    private $types = array(
        self::SOUND_TYPE_SOUND_LIST => 'Sound List',
//        self::SOUND_TYPE_NUMBER => 'Numbers',
        self::SOUND_TYPE_NUMBER_VARIABLE => 'Numbers Variable',
        self::SOUND_TYPE_TTS => 'TTS',
    );

    /** @var array HTTP请求方法 */
    private $apiMethod = array('get' => 'Get', 'post' => 'Post');

    /** @var array HTTP请求超时时间 */
    private $apiTimeout = array(1 => 1, 5 => 5, 10 => 10, 15 => 15, 20 => 20, 30 => 30, 60 => 60, 90 => 90);

    /**
     * @return Response
     */
    public function ivrAddAction()
    {
        return $this->render('IcsocIvrBundle:Ivr:ivr.html.twig');
    }

    /**
     * 编辑ivr
     * @param Request $request
     * @return Response
     */
    public function ivrEditAction(Request $request)
    {
        $ivrId = $request->get('id', 0);
        if (empty($ivrId)) {
            //todo 错误提示
        }

        $ivrInfo = $this->get('doctrine.dbal.default_connection')
            ->fetchAssoc("SELECT * FROM win_ivr WHERE ivr_id=:ivr_id LIMIT 1", array(':ivr_id' => $ivrId));
        $ivrContent = $ivrInfo['ivr_content'];
        $ivrContentArray = json_decode($ivrContent, true);
        //新版IVR内容为嵌套json格式，老版本为节点数组
        if (!empty($ivrInfo['ivr_ver'])) {
            $ivrContent = isset($ivrContentArray[0]) ? $ivrContentArray[0] : '';
            $ivrContentString = str_replace("\\", "\\\\", json_encode($ivrContent));
        } else {
            $ivrContentString = $ivrContent;
        }

        return $this->render(
            'IcsocIvrBundle:Ivr:ivr.html.twig',
            array(
                'ivr_id' => empty($ivrInfo['ivr_id']) ? 0 : $ivrInfo['ivr_id'],
                'ivr_name' => empty($ivrInfo['ivr_name']) ? '' : $ivrInfo['ivr_name'],
                'ivr_content' => $ivrContentString,
            )
        );
    }

    /**
     * 显示根节点的属性
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function rootNodeAttributeAction()
    {
        return $this->render('IcsocIvrBundle:Ivr:node_root_attr.html.twig', array(
            'nodes' => $this->nodes,
        ));
    }

    /**
     * 播放语音节点的属性
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function soundNodeAttributeAction()
    {
        $vccId = $this->get('security.token_storage')->getToken()->getUser()->getVccId();
        $sounds = $this->get('icsoc_data.model.sound')->getSoundsArray($vccId);

        return $this->render('IcsocIvrBundle:Ivr:node_sound_attr.html.twig', array(
            'sounds_type' => $this->types,
            'sounds_list' => $sounds,
            'play_times' => array(1 => 1, 2, 3, 4, 5, 6, 7, 8, 9, 10),
            'nodes' => $this->nodes,
        ));
    }

    /**
     * 按键导航节点属性
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function navigationNodeAttributeAction()
    {
        $vccId = $this->get('security.token_storage')->getToken()->getUser()->getVccId();
        $sounds = $this->get('icsoc_data.model.sound')->getSoundsArray($vccId);

        return $this->render(
            'IcsocIvrBundle:Ivr:node_navigation_attr.html.twig',
            array(
                'sounds_type' => $this->types,
                'sounds_list' => $sounds,
                'play_times' => array(1 => 1, 2, 3, 4, 5, 6, 7, 8, 9, 10),
                'timeout' => array(3 => 3, 6 => 6, 10 => 10, 20 => 20, 30 => 30, 40 => 40, 50 => 50, 60 => 60, 70 => 70, 80 => 80),
                'navigation_keys' => array(
                    '1' => 'key 1',
                    '2' => 'key 2',
                    '3' => 'key 3',
                    '4' => 'key 4',
                    '5' => 'key 5',
                    '6' => 'key 6',
                    '7' => 'key 7',
                    '8' => 'key 8',
                    '9' => 'key 9',
                    '0' => 'key 0',
                    '*' => 'key *',
                    '#' => 'key #',
                ),
                'nodes' => $this->nodes,
            )
        );
    }

    /**
     * 按键导航节点具体按键属性
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function navigationKeyNodeAttributeAction()
    {
        return $this->render('IcsocIvrBundle:Ivr:node_navigation_key_attr.html.twig', array(
            'nodes' => $this->nodes,
            'multi_keys_type' => array(
                'agent_num' => 'Agent Num',
                'phone_num' => 'Extension Num',
                'queue_num' => 'Queue Num',
            ),
        ));
    }

    /**
     * 转技能组节点属性
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function queueNodeAttributeAction()
    {
        $vccId = $this->getUser()->getVccId();
        $queues = $this->get('icsoc_data.model.queue')->getQueueNameKeyedByIdArray($vccId, true);

        $vccId = $this->get('security.token_storage')->getToken()->getUser()->getVccId();
        $sounds = $this->get('icsoc_data.model.sound')->getSoundsArray($vccId);

        return $this->render('IcsocIvrBundle:Ivr:node_queue_attr.html.twig', array(
            'queue' => $queues,
            'sounds_type' => $this->types,
            'sounds_list' => $sounds,
            'max_queue_times' => array(1 => 1, 2, 3, 4, 5, 6, 7, 8, 9, 10),
            'transfer_type' => array(
                'fixed' => 'Fixed Queue',
                'variable' => 'Based on variable',
                'memory' => 'Based on memory',
            ),
            'api_method' => $this->apiMethod,
            'api_timeout' => $this->apiTimeout,
        ));
    }

    /**
     * 转技能组节点子节点属性
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function queueChildrenNodeAttributeAction()
    {
        $vccId = $this->get('security.token_storage')->getToken()->getUser()->getVccId();
        $sounds = $this->get('icsoc_data.model.sound')->getSoundsArray($vccId);

        return $this->render('IcsocIvrBundle:Ivr:node_queue_children_attr.html.twig', array(
            'sounds_type' => $this->types,
            'sounds_list' => $sounds,
            'nodes' => $this->nodes,
        ));
    }

    /**
     * 留言节点属性
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function messageNodeAttributeAction()
    {
        $vccId = $this->get('security.token_storage')->getToken()->getUser()->getVccId();
        $sounds = $this->get('icsoc_data.model.sound')->getSoundsArray($vccId);

        return $this->render('IcsocIvrBundle:Ivr:node_message_attr.html.twig', array(
            'sounds_type' => $this->types,
            'sounds_list' => $sounds,
        ));
    }

    /**
     * 挂机节点属性
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function hangupNodeAttributeAction()
    {
        return $this->render('IcsocIvrBundle:Ivr:node_hangup_attr.html.twig');
    }

    /**
     * 收号节点属性
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function keysNodeAttributeAction()
    {
        $vccId = $this->get('security.token_storage')->getToken()->getUser()->getVccId();
        $sounds = $this->get('icsoc_data.model.sound')->getSoundsArray($vccId);

        return $this->render('IcsocIvrBundle:Ivr:node_keys_attr.html.twig', array(
            'sounds_type' => $this->types,
            'sounds_list' => $sounds,
            'play_times' => array(1 => 1, 2, 3, 4, 5, 6, 7, 8, 9, 10),
            'timeout' => array(
                3 => 3, 5 => 5, 10 => 10, 20 => 20, 30 => 30, 40 => 40, 50 => 50,
                60 => 60, 70 => 70, 80 => 80, 90 => 90, 100 => 100,
            ),
        ));
    }

    /**
     * 收号节点子节点属性
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function keysChildrenNodeAttributeAction()
    {
        return $this->render('IcsocIvrBundle:Ivr:node_keys_children_attr.html.twig', array(
            'nodes' => $this->nodes,
        ));
    }

    /**
     * 接口交互节点属性
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function httpNodeAttributeAction()
    {
        return $this->render(
            'IcsocIvrBundle:Ivr:node_http_attr.html.twig',
            array(
                'request_method' => $this->apiMethod,
                'timeout' => $this->apiTimeout,
            )
        );
    }

    /**
     * 接口交互节点子节点属性
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function httpChildrenNodeAttributeAction()
    {
        return $this->render('IcsocIvrBundle:Ivr:node_http_children_attr.html.twig', array(
            'nodes' => $this->nodes,
        ));
    }

    /**
     * 来电记忆节点属性
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function memoryNodeAttributeAction()
    {
        $vccId = $this->getUser()->getVccId();
        $queues = $this->get('icsoc_data.model.queue')->getQueueNameKeyedByIdArray($vccId, true);

        return $this->render('IcsocIvrBundle:Ivr:node_memory_attr.html.twig', array(
            'queue' => $queues,
            'memory_type' => array(
                1 => 'Call cdr',
                2 => 'Belong to agent',
                3 => 'Custom api',
            ),
            'cdr_type' => array(
                'all' => 'All',
                'inbound' => 'Inbound',
                'outbound' => 'Outbound',
            ),
            'last_call_time' => array(
                1 => 1,
                2 => 2,
                3 => 3,
                4 => 4,
                5 => 5,
                6 => 6,
                7 => 7,
                8 => 8,
                9 => 9,
                10 => 10,
                11 => 11,
                12 => 12,
                24 => 24,
                48 => 48,
                72 => 72,
            ),
            'time_unit' => array(
                'hour' => 'Hour',
                'day' => 'Day',
                'month' => 'Month',
            ),
        ));
    }

    /**
     * 转电话节点属性
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function phoneNodeAttributeAction()
    {
        //设置主叫号码
        $vccId = $this->getUser()->getVccId();
        $callers = $this->get('icsoc_data.model.relaynumber')->getAllPhoneArray($vccId);
        $callersArray = array();
        foreach ($callers as $caller) {
            $callersArray[$caller['phone']] = $caller['phone'];
        }

        return $this->render('IcsocIvrBundle:Ivr:node_phone_attr.html.twig', array(
            'caller' => $callersArray,
            'phone_line' => array(
                0 => 'Outside Phone',
                1 => 'Inside Phone',
            ),
            'phone_type' => array(
                'fixed' => 'Fixed phone',
                'variable' => 'Based on variable',
            ),
            'caller_type' => array(
                'select' => 'Select Caller',
                'caller_variable' => 'Variable Type',
            ),
            'nodes' => $this->nodes,
        ));
    }

    /**
     * 转坐席节点属性
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function agentNodeAttributeAction()
    {
        $vccId = $this->getUser()->getVccId();
        $agents = $this->get('icsoc_data.model.agent')->getAgentNameKeyedByIdArray($vccId);

        return $this->render('IcsocIvrBundle:Ivr:node_agent_attr.html.twig', array(
            'transfer_type' => array(
                'fixed' => 'Fixed agent',
                'variable' => 'Based on variable',
                'memory' => 'Based on memory',
            ),
            'agent' => $agents,
            'transfer_mode' => array(
                1 => 'Only transfer to ready agents',
                2 => 'Only transfer to mobile',
                3 => 'Only when agent login transfer to agent, otherwise transfer to mobile',
                4 => 'When agent login first transfer to agent, if fails then transfer to mobile',
            ),
            'nodes' => $this->nodes,
        ));
    }

    /**
     * 判断节点属性
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function judgeNodeAttributeAction()
    {
        return $this->render('IcsocIvrBundle:Ivr:node_judge_attr.html.twig');
    }

    /**
     * 判断子节点属性
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function judgeChildrenNodeAttributeAction()
    {
        return $this->render('IcsocIvrBundle:Ivr:node_judge_children_attr.html.twig', array(
            'nodes' => $this->nodes,
        ));
    }

    /**
     * 转IVR节点属性
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function IvrNodeAttributeAction(Request $request)
    {
        $list = $this->get('doctrine.dbal.default_connection')->fetchAll(
            "SELECT ivr_code,ivr_name FROM win_ivr WHERE vcc_id = ? AND ivr_id != ?",
            array($this->getVccId(), trim($request->get('ivr_id')))
        );
        
        return $this->render('IcsocIvrBundle:Ivr:node_ivr_attr.html.twig', array(
            'ivr_list' => $list,
        ));
    }

    /**
     * 获取某一ivr 的节点信息；
     * @param Request $request
     * @return JsonResponse
     */
    public function IvrGetNodeAction(Request $request)
    {
        $ivrCode = $request->get('ivr_code', 0);
        $ivrInfo = $this->get('doctrine.dbal.default_connection')->fetchColumn(
            "SELECT ivr_info FROM win_ivr WHERE ivr_code = ?AND vcc_id = ? LIMIT 1",
            array($ivrCode, $this->getVccId())
        );
        $ivrInfoRow = json_decode($ivrInfo, true);
        $nodeTree = array();
        if (!empty($ivrInfoRow)) {
            $nodeTree = $this->handleIvrNode($ivrInfoRow, 'node0');
        }

        return new JsonResponse($nodeTree);
    }

    /**
     * 播放语音
     *
     * @param Request $request
     *
     * @return Response
     */
    public function playSoundAction(Request $request)
    {

        $file = $request->get('file');

        if (empty($file)) {
            return new Response();
        }
        /*
             $extend = pathinfo($file);
             $extend = empty($extend['extension']) ? '' : strtolower($extend['extension']);
             if ($extend == 'mp3') {
                 $contentType = 'audio/mp3';
             } elseif ($extend == 'wav') {
                 $contentType = 'audio/x-wav';
             } else {
                 $contentType = 'audio/x-wav';
             }

             return new Response(file_get_contents($file), 200, array(
                 'Pragma' => 'Public',
                 'Expires' => 0,
                 'Cache-Component' => 'must-revalidate, post-check=0, pre-check=0',
                 'Content-type' => $contentType,
                 'Content-Length' => filesize($file),
                 'Content-Transfer-Encoding' => 'binary',
                 'Accept-Ranges' => 'bytes',
             ));*/

        $flysystem = $this->get("icsoc_filesystem");
        if ($flysystem->has($file)) {
            $content = $flysystem->read($file);

            return new Response($content, 200, array(
                'Pragma' => 'Public',
                'Expires' => 0,
                'Cache-Component' => 'must-revalidate, post-check=0, pre-check=0',
                'Content-type' => 'audio/x-wav',
                'Content-Length' => strlen($content),
                'Content-Transfer-Encoding' => 'binary',
                'Accept-Ranges' => 'bytes',
                'Content-Disposition' => 'attachment;filename='.basename($file),
            ));
        } else {
            return new Response("语音不存在");
        }
    }

    /**
     * 异步加载语音列表
     *
     * @return JsonResponse
     */
    public function refreshSoundAction()
    {
        $vccId = $this->getUser()->getVccId();
        $sounds = $this->get('icsoc_data.model.sound')->getSoundsArray($vccId);

        return new JsonResponse($sounds);
    }

    /**
     * 保存IVR信息
     * @param Request $request
     *
     * @return JsonResponse
     */
    public function saveIvrAction(Request $request)
    {
        //$logger = $this->container->get('logger');
        $ivrString = $request->get('ivrString', '');
        $ivrName = $request->get('ivr_name', '');
        $ivrId = $request->get('ivr_id', 0);
        $translator = $this->get('translator');
        if (empty($ivrName)) {
            return new JsonResponse(array(
                'code' => 400,
                'message' => $translator->trans('Ivr name is empty'),
            ));
        }
//        $redis = new Client(
//            array(
//                'host' => $this->container->getParameter('redis.host'),
//                'port' => $this->container->getParameter('redis.port'),
//            ),
//            array('prefix' => $this->container->getParameter('redis.prefix'))
//        );
        $conn = $this->get('doctrine.dbal.default_connection');
        //验证IVR名称是否重复
        $count = $conn->fetchColumn(
            "SELECT COUNT(*)
            FROM win_ivr
            WHERE vcc_id =:vcc_id AND ivr_id !=:ivr_id AND ivr_name =:ivr_name ",
            array(':vcc_id' => $this->getUser()->getVccId(), ':ivr_id' => $ivrId, ':ivr_name' => $ivrName)
        );


        if (!empty($count)) {
            return new JsonResponse(array(
                'code' => 409,
                'message' => $translator->trans('Ivr name Already exists'),
            ));
        }

        if (empty($ivrString)) {
            return new JsonResponse(array(
                'code' => 401,
                'message' => $translator->trans('Ivr is empty'),
            ));
        }

        $ivrArray = json_decode($ivrString, true);
        if (json_last_error() != JSON_ERROR_NONE) {
            return new JsonResponse(array(
                'code' => 402,
                'message' => $translator->trans(
                    'Ivr decode fail, the error is %error%',
                    array('%error%' => json_last_error())
                ),
            ));
        }
        if (empty($ivrArray[0])) {
            return new JsonResponse(array(
                'code' => 403,
                'message' => $translator->trans('Ivr is empty'),
            ));
        }

        $parsedArray = $this->parseIvrInfo($ivrArray);

        //不存在ivrId则为新建
        if (empty($ivrId)) {
            $conn->beginTransaction();

            try {
                $data = array(
                    'ivr_name' => $ivrName,
                    'ivr_content' => $ivrString,
                    'ivr_info' => json_encode($parsedArray),
                    'add_time' => time(),
                    'update_time' => time(),
                    'vcc_id' => $this->getUser()->getVccId(),
                    'vcc_code' => $this->getUser()->getVccCode(),
                    'ivr_ver' => 1,
                );
                $result = $conn->insert('win_ivr', $data);
                $ivrId = $conn->lastInsertId();

                if ($result) {
                    $vccId = $this->getUser()->getVccId();
                    $result = $this->sendNoticeMessage($ivrId, $vccId, 'create');
                    if ($result === false) {
                        $conn->rollBack();

                        return new JsonResponse(array(
                            'code' => 408,
                            'message' => '数据保存失败',
                        ));
                    }

                    $ivrCode = 'ivr'.$this->getUser()->getVccId().'_'.$ivrId;
                    $conn->update(
                        'win_ivr',
                        array(
                            'ivr_code' => $ivrCode,
                        ),
                        array(
                            'ivr_id' => $ivrId,
                        )
                    );

                    //写入操作日志
                    $str = "[ivr_id]:$ivrId [ivr_name]:$ivrName [ivr_code]:ivr".$this->getUser()->getVccId()."_".$ivrId;
                    $logStr = $this->get('translator')->trans('Logs Add IVR %str%', array('%str%' => $str));
                    $this->get('icsoc_core.helper.logger')->actionLog(ActionLogger::ACTION_ADD, $logStr);
                    //放入redis中
                    $this->get('snc_redis.default')->set($ivrCode, $data['ivr_info']);
                    $conn->commit();

                    return new JsonResponse(array(
                        'code' => 200,
                        'message' => $translator->trans('Save success'),
                        'ivr_id' => $ivrId,
                    ));
                }
            } catch (\Exception $e) {
                $conn->rollBack();

                return new JsonResponse(array(
                    'code' => 408,
                    'message' => '数据保存失败',
                    'ivr_id' => $ivrId,
                ));
            }
        } else {
            $conn->beginTransaction();

            try {
                $oldIvrInfo = $conn->fetchAssoc(
                    'SELECT ivr_name,ivr_code
                    FROM win_ivr
                    WHERE ivr_id = '.$ivrId
                );
                $data = array(
                    'ivr_name' => $ivrName,
                    'ivr_content' => $ivrString,
                    'ivr_info' => json_encode($parsedArray),
                    'update_time' => time(),
                );
                $result = $conn->update('win_ivr', $data, array('ivr_id' => $ivrId));

                if ($result) {
                    $result = $this->sendNoticeMessage(
                        $ivrId,
                        $this->getUser()->getVccId(),
                        'update'
                    );
                    if ($result === false) {
                        $conn->rollBack();

                        return new JsonResponse(array(
                            'code' => 408,
                            'message' => '数据保存失败',
                        ));
                    }

                    //修改日程规则中相关
                    $conn->update("win_rules", array('ivr_name' => $ivrName), array('ivr_id' => $ivrId));
                    //放入redis中
                    $this->get('snc_redis.default')->set($oldIvrInfo['ivr_code'], $data['ivr_info']);
                    //写入操作日志
                    $str = "[ivr_id]:$ivrId [ivr_name]:{$oldIvrInfo['ivr_name']}=>$ivrName";
                    $logStr = $this->get('translator')->trans('Logs Update IVR %str%', array('%str%' => $str));
                    $this->get('icsoc_core.helper.logger')->actionLog(ActionLogger::ACTION_UPDATE, $logStr);
                    $conn->commit();

                    return new JsonResponse(array(
                        'code' => 200,
                        'message' => $translator->trans('Save success'),
                        'ivr_id' => $ivrId,
                    ));
                }
            } catch (\Exception $e) {
                $conn->rollBack();

                return new JsonResponse(array(
                    'code' => 408,
                    'message' => '数据保存失败',
                    'ivr_id' => $ivrId,
                ));
            }
        }

        if ($result > 0) {
            return new JsonResponse(array(
                'code' => 200,
                'message' => $translator->trans('Save success'),
                'ivr_id' => $ivrId,
            ));
        } else {
            return new JsonResponse(array(
                'code' => 404,
                'message' => $translator->trans('Save failure'),
            ));
        }
    }

    /**
     * ivr 列表
     * @return Response
     */
    public function listAction()
    {
        return $this->render("IcsocIvrBundle:Ivr:list.html.twig");
    }

    /**
     * ivr 列表数据
     * @param Request $request
     * @return Response
     */
    public function listDataAction(Request $request)
    {
        $page = $request->get('page', 1);
        $rows = $request->get('rows', 10);
        $sord = $request->get('sord', 'asc');
        $sidx = $request->get('sidx', 'ivrId');
        $fliter = $request->get('fliter', '');
        $where = ' AND intro.vccId = :vcc_id ';
        $parameter['vcc_id'] = $this->getUser()->getVccId();
        if (!empty($fliter)) {
            $json = json_decode($fliter, true);
            if (isset($json['keyword']) && !empty($json['keyword'])) {
                $where .= "AND intro.ivrName like '%".$json['keyword']."%'";
            }
        }

        /** @var \Doctrine\ORM\EntityManagerInterface $em */
        $em = $this->getDoctrine()->getManager();
        $query = $em->createQuery(
            "SELECT count(intro)
            FROM IcsocSecurityBundle:WinIvr intro
            WHERE 1 = 1 ".$where
        )->setParameters($parameter);
        try {
            $single = $query->getSingleResult();
            $count = $single['1'];
        } catch (NoResultException $e) {
            $count = 0;
        }
        if ($count > 0) {
            $totalPage = ceil($count / $rows);
        } else {
            $totalPage = 1;
        }
        if ($page > $totalPage) {
            $page = $totalPage;
        }
        $start = ($page - 1) * $rows;

        /** @var \Doctrine\ORM\Query $query */
        $query = $em->createQuery(
            'SELECT intro.ivrId AS ivr_id,intro.ivrName AS ivr_name,intro.ivrCode AS ivr_code,intro.remark,
            intro.updateTime
            FROM IcsocSecurityBundle:WinIvr intro
            WHERE 1=1 '.$where.' ORDER BY intro.'.$sidx.' '.$sord
        )->setParameters($parameter);

        $query->setFirstResult($start);
        $query->setMaxResults($rows);
        $all = $query->getResult();
        foreach ($all as $k => $v) {
            $all[$k]['update_time'] = date("Y-m-d H:i:s", $v['updateTime']);
        }
        $reponse['rows'] = $all;
        $reponse['page'] = $page;
        $reponse['total'] = $totalPage;
        $reponse['records'] = $count;

        return new JsonResponse($reponse);
    }

    /**
     * 删除ivr
     * @param Request $request
     * @return JsonResponse
     */
    public function delAction(Request $request)
    {
        $ids = $request->get('id', 0);
        $em = $this->getDoctrine()->getManager();
        $where = "ivr.ivrId IN ($ids)";
        $res = $em->getRepository("IcsocSecurityBundle:WinIvr")->delIvr($where);
        if ($res) {
            $ivrids = explode(',', $ids);
            foreach ($ivrids as $id) {
                $this->sendNoticeMessage($id, $this->getUser()->getVccId(), 'delete');
            }

            $logStr = $this->get('translator')->trans('Logs Delete IVR %str%', array('%str%' => $ids));
            $this->get('icsoc_core.helper.logger')->actionLog(ActionLogger::ACTION_DELETE, $logStr);
            $message = 'Delete success';
            $error = false;
        } else {
            $message = 'Delete fail';
            $error = true;
        }

        return new JsonResponse(array('message' => $this->get('translator')->trans($message), 'error' => $error));
    }

    /**
     * 复制IVR流程
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function copyIvrAction(Request $request)
    {
        $translator = $this->get('translator');

        $ivrCopyId = $request->get('ivr_id', 0);
        $ivrName = $request->get('ivr_name', '');

        if (empty($ivrName)) {
            return new JsonResponse(array(
                'code' => 400,
                'message' => $translator->trans('Ivr name is empty'),
            ));
        }

        $conn = $this->get('doctrine.dbal.default_connection');
        //验证IVR名称是否重复
        $count = $conn->fetchColumn(
            "SELECT COUNT(*)
            FROM win_ivr
            WHERE vcc_id =:vcc_id AND ivr_name =:ivr_name ",
            array(':vcc_id' => $this->getUser()->getVccId(), ':ivr_name' => $ivrName)
        );

        if (!empty($count)) {
            return new JsonResponse(array(
                'code' => 409,
                'message' => $translator->trans('Ivr name Already exists'),
            ));
        }

        $vccId = $this->getUser()->getVccId();
        $vccCode = $this->getUser()->getVccCode();

        //查询复制的流程
        $ivrInfo = $conn->fetchAssoc(
            "SELECT ivr_code,ivr_name,ivr_content,ivr_info
            FROM win_ivr
            WHERE vcc_id =:vcc_id AND ivr_id =:ivr_id ",
            array(':vcc_id' => $vccId, ':ivr_id' => $ivrCopyId)
        );

        $data = array(
            'ivr_name' => $ivrName,
            'ivr_content' => $ivrInfo['ivr_content'],
            'ivr_info' => $ivrInfo['ivr_info'],
            'add_time' => time(),
            'update_time' => time(),
            'vcc_id' => $vccId,
            'vcc_code' => $vccCode,
            'ivr_ver' => 1,
        );

        $conn->beginTransaction();
        $conn->insert('win_ivr', $data);
        $ivrId = $conn->lastInsertId();

        $result = $this->sendNoticeMessage($ivrId, $vccId, 'create');

        if ($result === false) {
            $conn->rollBack();

            return new JsonResponse(array(
                'code' => 408,
                'message' => '数据保存失败',
            ));
        }

        $conn->commit();

        $ivrCode = 'ivr'.$vccId.'_'.$ivrId;
        $conn->update(
            'win_ivr',
            array(
                'ivr_code' => $ivrCode,
            ),
            array(
                'ivr_id' => $ivrId,
            )
        );

//        $redis = new Client(
//            array(
//                'host' => $this->container->getParameter('redis.host'),
//                'port' => $this->container->getParameter('redis.port'),
//            ),
//            array('prefix' => $this->container->getParameter('redis.prefix'))
//        );
//        $redis->set($ivrCode, $data['ivr_info']);
        $this->get('snc_redis.default')->set($ivrCode, $data['ivr_info']);

        //写入操作日志
        $str = "[ivr_id]:$ivrCopyId=>$ivrId [ivr_name]:$ivrInfo[ivr_name]=>$ivrName [ivr_code]:$ivrInfo[ivr_code]=>ivr".$vccId.'_'.$ivrId;
        $logStr = $this->get('translator')->trans('Logs Copy IVR %str%', array('%str%' => $str));
        $this->get('icsoc_core.helper.logger')->actionLog(ActionLogger::ACTION_ADD, $logStr);

        return new JsonResponse(array(
            'code' => 200,
            'message' => $translator->trans('Save success'),
            'ivr_id' => $ivrId,
        ));
    }

    /**
     * 添加备注
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function remarkAddAction(Request $request)
    {
        $translator = $this->get('translator');

        $ivrId = $request->get('ivr_id', 0);
        $remark = $request->get('remark', '');

        if (empty($remark) || empty($ivrId)) {
            return new JsonResponse(array(
                'code' => 400,
                'message' => $translator->trans('Param is empty'),
            ));
        }

        $conn = $this->get('doctrine.dbal.default_connection');
        $conn->update('win_ivr', array('remark' => $remark), array('ivr_id' => $ivrId));

        return new JsonResponse(array(
            'code' => 200,
            'message' => $translator->trans('Save success'),
        ));
    }

    /**
     * 解析ivr信息
     *
     * @param array $ivrArray json_decode后的数组
     *
     * @return bool|array
     */
    public function parseIvrInfo($ivrArray)
    {
        if (empty($ivrArray) || !is_array($ivrArray)) {
            return false;
        }
        $parsedArray = array();
        foreach ($ivrArray as $ivrNode) {
            $nodeType = isset($ivrNode['type']) ? $ivrNode['type'] : 0;
            $nodeId = isset($ivrNode['tId']) ? str_replace('tree_', 'node', $ivrNode['tId']) : '';
            $parentId = isset($ivrNode['parentTId']) ? str_replace('tree_', 'node', $ivrNode['parentTId']) : null;

            switch ($nodeType) {
                case NodesType::NODE_TYPE_ROOT://根节点
                    $attr = array(
                        'name' => isset($ivrNode['name']) ? $ivrNode['name'] : '',
                        'id' => $nodeId,
                        'type' => $nodeType,
                    );
                    if (!isset($parsedArray[$nodeId])) {
                        $parsedArray[$nodeId] = $attr;
                    } else {
                        array_merge($parsedArray[$nodeId], $attr);
                    }
                    break;
                case NodesType::NODE_TYPE_SOUND://放音节点
                    //设置当前节点的信息
                    $attr = array(
                        'name' => isset($ivrNode['name']) ? $ivrNode['name'] : '',
                        'id' => $nodeId,
                        'parentId' => $parentId,
                        'type' => $nodeType,
                        'sound' => isset($ivrNode['sound']) ? $ivrNode['sound'] : '',
                        'bkeystop' => isset($ivrNode['bkeystop']) ? $ivrNode['bkeystop'] : 0,
                        'play_times' => isset($ivrNode['play_times']) ? $ivrNode['play_times'] : 1,
                    );
                    if (!isset($parsedArray[$nodeId])) {
                        $parsedArray[$nodeId] = $attr;
                    } else {
                        array_merge($parsedArray[$nodeId], $attr);
                    }
                    //更新父节点的jump字段
                    if (isset($parsedArray[$parentId])) {
                        $parsedArray[$parentId]['jump'] = $nodeId;
                    } else {
                        $parsedArray[$parentId] = array(
                            'jump' => $nodeId,
                        );
                    }
                    break;
                case NodesType::NODE_TYPE_NAVIGATION://按键导航
                    $attr = array(
                        'name' => isset($ivrNode['name']) ? $ivrNode['name'] : '',
                        'id' => $nodeId,
                        'parentId' => $parentId,
                        'type' => $nodeType,
                        'navigation_sound' => isset($ivrNode['navigation_sound']) ? $ivrNode['navigation_sound'] : '',
                        'timeout' => isset($ivrNode['timeout']) ? $ivrNode['timeout'] : 0,
                        'play_times' => isset($ivrNode['play_times']) ? $ivrNode['play_times'] : 1,
                        'navigation_keys' => isset($ivrNode['navigation_keys']) ? $ivrNode['navigation_keys'] : '',
                        'error_key_sound' => isset($ivrNode['error_key_sound']) ? $ivrNode['error_key_sound'] : '',
                        'none_key_sound' => isset($ivrNode['none_key_sound']) ? $ivrNode['none_key_sound'] : '',
                        'if_enable_multi_key' => isset($ivrNode['if_enable_multi_key'])
                            ? $ivrNode['if_enable_multi_key'] : 0,
                        'multi_keys_start' => isset($ivrNode['multi_keys_start'])
                            ? $ivrNode['multi_keys_start'] : '',
                        'multi_keys_length' => isset($ivrNode['multi_keys_length']) ? $ivrNode['multi_keys_length'] : 0,
                    );
                    if (!isset($parsedArray[$nodeId])) {
                        $parsedArray[$nodeId] = $attr;
                    } else {
                        array_merge($parsedArray[$nodeId], $attr);
                    }
                    //更新父节点的jump字段
                    if (isset($parsedArray[$parentId])) {
                        $parsedArray[$parentId]['jump'] = $nodeId;
                    } else {
                        $parsedArray[$parentId] = array(
                            'jump' => $nodeId,
                        );
                    }
                    break;
                case NodesType::NODE_TYPE_NAVIGATION_KEY://按键导航具体按键
                    if (isset($ivrNode['condition']) && $ivrNode['condition'] == 'multiKeys') {
                        $name = 'multiKeys';
                    } else {
                        $name = isset($ivrNode['name']) ? $ivrNode['name'] : '';
                    }
                    $attr = array(
                        'name' => $name,
                        'id' => $nodeId,
                        'parentId' => $parentId,
                        'type' => $nodeType,
                    );

                    if (isset($ivrNode['condition']) && isset($ivrNode['condition']) == 'multiKeys') {
                        $attr['multi_keys_type'] = isset($ivrNode['multi_keys_type']) ? $ivrNode['multi_keys_type'] : 0;
                        $attr['variable_name'] = isset($ivrNode['variable_name']) ? $ivrNode['variable_name'] : 0;
                        $attr['is_tran_front'] = isset($ivrNode['is_tran_front']) ? $ivrNode['is_tran_front'] : 0;
                    }

                    if (!isset($parsedArray[$nodeId])) {
                        $parsedArray[$nodeId] = $attr;
                    } else {
                        array_merge($parsedArray[$nodeId], $attr);
                    }
                    //设置父节点中子节点的信息
                    if (!isset($parsedArray[$parentId])) {
                        $parsedArray[$parentId] = array(
                            'children' => array($nodeId => $name),
                        );
                    } else {
                        if (isset($parsedArray[$parentId]['children'])) {
                            $parsedArray[$parentId]['children'][$name] = $nodeId;
                        } else {
                            $parsedArray[$parentId]['children'] = array($name => $nodeId);
                        }
                    }
                    break;
                case NodesType::NODE_TYPE_QUEUE://转技能组节点
                    $attr = array(
                        'name' => isset($ivrNode['name']) ? $ivrNode['name'] : '',
                        'id' => $nodeId,
                        'parentId' => $parentId,
                        'type' => $nodeType,
                        'transfer_type' => isset($ivrNode['transfer_type']) ? $ivrNode['transfer_type'] : 0,
                        'variable_name' => isset($ivrNode['variable_name']) ? $ivrNode['variable_name'] : '',
                        'queue' => isset($ivrNode['queue']) ? $ivrNode['queue'] : 0,
                        'sound' => isset($ivrNode['sound']) ? $ivrNode['sound'] : '',
                        'if_enable_queue_timeout_continue' => isset($ivrNode['if_enable_queue_timeout_continue']) ?
                            $ivrNode['if_enable_queue_timeout_continue'] : 0,
                        'max_queue_times' => isset($ivrNode['max_queue_times']) ? $ivrNode['max_queue_times'] : 0,
                        'before_conn_sound' => isset($ivrNode['before_conn_sound']) ?
                            $ivrNode['before_conn_sound'] : '',
                        'agent_side_sound' => isset($ivrNode['agent_side_sound']) ? $ivrNode['agent_side_sound'] : '',
                        'if_handle_none_agent' => isset($ivrNode['if_handle_none_agent']) ?
                            $ivrNode['if_handle_none_agent'] : 0,
                        'if_handle_queue_times_exceed' => isset($ivrNode['if_handle_queue_times_exceed']) ?
                            $ivrNode['if_handle_queue_times_exceed'] : 0,
                        'if_handle_queue_full' => isset($ivrNode['if_handle_queue_full']) ?
                            $ivrNode['if_handle_queue_full'] : 0,
                        'if_handle_queue_timeout' => isset($ivrNode['if_handle_queue_timeout']) ?
                            $ivrNode['if_handle_queue_timeout'] : 0,
                        'if_open_vip' => isset($ivrNode['if_open_vip']) ? $ivrNode['if_open_vip'] : 0,
                        'api_url' => isset($ivrNode['api_url']) ? $ivrNode['api_url'] : '',
                        'api_method' => isset($ivrNode['api_method']) ? $ivrNode['api_method'] : '',
                        'api_timeout' => isset($ivrNode['api_timeout']) ? $ivrNode['api_timeout'] : '',
                        'api_params' => isset($ivrNode['api_params']) ? $ivrNode['api_params'] : '',
                    );
                    if (!isset($parsedArray[$nodeId])) {
                        $parsedArray[$nodeId] = $attr;
                    } else {
                        array_merge($parsedArray[$nodeId], $attr);
                    }
                    //更新父节点的jump字段
                    if (isset($parsedArray[$parentId])) {
                        $parsedArray[$parentId]['jump'] = $nodeId;
                    } else {
                        $parsedArray[$parentId] = array(
                            'jump' => $nodeId,
                        );
                    }
                    break;
                case NodesType::NODE_TYPE_QUEUE_CHILDREN://转技能组子节点
                    $attr = array(
                        'name' => isset($ivrNode['name']) ? $ivrNode['name'] : '',
                        'id' => $nodeId,
                        'parentId' => $parentId,
                        'type' => $nodeType,
                        'sound' => isset($ivrNode['sound']) ? $ivrNode['sound'] : '',
                    );
                    //是否设置了本身节点
                    if (!isset($parsedArray[$nodeId])) {
                        $parsedArray[$nodeId] = $attr;
                    } else {
                        array_merge($parsedArray[$nodeId], $attr);
                    }
                    //设置父节点中子节点的信息
                    $condition = isset($ivrNode['condition']) ? $ivrNode['condition'] : '';
                    if (!isset($parsedArray[$parentId])) {
                        $parsedArray[$parentId] = array(
                            'children' => array($condition => $nodeId),
                        );
                    } else {
                        if (isset($parsedArray[$parentId]['children'])) {
                            $parsedArray[$parentId]['children'][$condition] = $nodeId;
                        } else {
                            $parsedArray[$parentId]['children'] = array($condition => $nodeId);
                        }
                    }
                    break;
                case NodesType::NODE_TYPE_MESSAGE://留言节点
                    $attr = array(
                        'name' => isset($ivrNode['name']) ? $ivrNode['name'] : '',
                        'id' => $nodeId,
                        'parentId' => $parentId,
                        'type' => $nodeType,
                        'sound' => isset($ivrNode['sound']) ? $ivrNode['sound'] : '',
                    );
                    if (!isset($parsedArray[$nodeId])) {
                        $parsedArray[$nodeId] = $attr;
                    } else {
                        array_merge($parsedArray[$nodeId], $attr);
                    }
                    //更新父节点的jump字段
                    if (isset($parsedArray[$parentId])) {
                        $parsedArray[$parentId]['jump'] = $nodeId;
                    } else {
                        $parsedArray[$parentId] = array(
                            'jump' => $nodeId,
                        );
                    }
                    break;
                case NodesType::NODE_TYPE_HANGUP://挂机节点
                    $attr = array(
                        'name' => isset($ivrNode['name']) ? $ivrNode['name'] : '',
                        'id' => $nodeId,
                        'parentId' => $parentId,
                        'type' => $nodeType,
                    );
                    if (!isset($parsedArray[$nodeId])) {
                        $parsedArray[$nodeId] = $attr;
                    } else {
                        array_merge($parsedArray[$nodeId], $attr);
                    }
                    //更新父节点的jump字段
                    if (isset($parsedArray[$parentId])) {
                        $parsedArray[$parentId]['jump'] = $nodeId;
                    } else {
                        $parsedArray[$parentId] = array(
                            'jump' => $nodeId,
                        );
                    }
                    break;
                case NodesType::NODE_TYPE_KEYS://收号节点
                    $attr = array(
                        'name' => isset($ivrNode['name']) ? $ivrNode['name'] : '',
                        'id' => $nodeId,
                        'parentId' => $parentId,
                        'type' => $nodeType,
                        'sound' => isset($ivrNode['sound']) ? $ivrNode['sound'] : '',
                        'play_times' => isset($ivrNode['play_times']) ? $ivrNode['play_times'] : 1,
                        'max_keys_length' => isset($ivrNode['max_keys_length']) ? $ivrNode['max_keys_length'] : 0,
                        'timeout' => isset($ivrNode['timeout']) ? $ivrNode['timeout'] : 0,
                        'variable_name' => isset($ivrNode['variable_name']) ? $ivrNode['variable_name'] : '',
                        'is_tran_front' => isset($ivrNode['is_tran_front']) ? $ivrNode['is_tran_front'] : 0,
                    );
                    if (!isset($parsedArray[$nodeId])) {
                        $parsedArray[$nodeId] = $attr;
                    } else {
                        array_merge($parsedArray[$nodeId], $attr);
                    }
                    //更新父节点的jump字段
                    if (isset($parsedArray[$parentId])) {
                        $parsedArray[$parentId]['jump'] = $nodeId;
                    } else {
                        $parsedArray[$parentId] = array(
                            'jump' => $nodeId,
                        );
                    }
                    break;
                case NodesType::NODE_TYPE_KEYS_CHILDREN://收号节点子节点
                    $attr = array(
                        'name' => isset($ivrNode['name']) ? $ivrNode['name'] : '',
                        'id' => $nodeId,
                        'parentId' => $parentId,
                        'type' => $nodeType,
                    );
                    //是否设置了本身节点
                    if (!isset($parsedArray[$nodeId])) {
                        $parsedArray[$nodeId] = $attr;
                    } else {
                        array_merge($parsedArray[$nodeId], $attr);
                    }
                    //设置父节点中子节点的信息
                    $condition = isset($ivrNode['condition']) ? $ivrNode['condition'] : '';
                    if (!isset($parsedArray[$parentId])) {
                        $parsedArray[$parentId] = array(
                            'children' => array($condition => $nodeId),
                        );
                    } else {
                        if (isset($parsedArray[$parentId]['children'])) {
                            $parsedArray[$parentId]['children'][$condition] = $nodeId;
                        } else {
                            $parsedArray[$parentId]['children'] = array($condition => $nodeId);
                        }
                    }
                    break;
                case NodesType::NODE_TYPE_HTTP://http接口节点
                    $attr = array(
                        'name' => isset($ivrNode['name']) ? $ivrNode['name'] : '',
                        'id' => $nodeId,
                        'parentId' => $parentId,
                        'type' => $nodeType,
                        'api_url' => isset($ivrNode['api_url']) ? $ivrNode['api_url'] : '',
                        'api_params' => isset($ivrNode['api_params']) ? $ivrNode['api_params'] : '',
                        'request_method' => isset($ivrNode['request_method']) ? $ivrNode['request_method'] : 'get',
                        'timeout' => isset($ivrNode['timeout']) ? $ivrNode['timeout'] : 1,
                        'variable_names' => isset($ivrNode['variable_name']) ? $ivrNode['variable_name'] : '',
                        'is_tran_front' => isset($ivrNode['is_tran_front']) ? $ivrNode['is_tran_front'] : 0,
                    );
                    if (!isset($parsedArray[$nodeId])) {
                        $parsedArray[$nodeId] = $attr;
                    } else {
                        array_merge($parsedArray[$nodeId], $attr);
                    }
                    //更新父节点的jump字段
                    if (isset($parsedArray[$parentId])) {
                        $parsedArray[$parentId]['jump'] = $nodeId;
                    } else {
                        $parsedArray[$parentId] = array(
                            'jump' => $nodeId,
                        );
                    }
                    break;
                case NodesType::NODE_TYPE_HTTP_CHILDREN://http接口子节点
                    $attr = array(
                        'name' => isset($ivrNode['name']) ? $ivrNode['name'] : '',
                        'id' => $nodeId,
                        'parentId' => $parentId,
                        'type' => $nodeType,
                    );
                    //是否设置了本身节点
                    if (!isset($parsedArray[$nodeId])) {
                        $parsedArray[$nodeId] = $attr;
                    } else {
                        array_merge($parsedArray[$nodeId], $attr);
                    }
                    //设置父节点中子节点的信息
                    $condition = isset($ivrNode['condition']) ? $ivrNode['condition'] : '';
                    if (!isset($parsedArray[$parentId])) {
                        $parsedArray[$parentId] = array(
                            'children' => array($condition => $nodeId),
                        );
                    } else {
                        if (isset($parsedArray[$parentId]['children'])) {
                            $parsedArray[$parentId]['children'][$condition] = $nodeId;
                        } else {
                            $parsedArray[$parentId]['children'] = array($condition => $nodeId);
                        }
                    }
                    break;
                case NodesType::NODE_TYPE_CALL_MEMORY://来电记忆节点
                    $attr = array(
                        'name' => isset($ivrNode['name']) ? $ivrNode['name'] : '',
                        'id' => $nodeId,
                        'parentId' => $parentId,
                        'type' => $nodeType,
                        'memory_type' => isset($ivrNode['memory_type']) ? $ivrNode['memory_type'] : 0,
                        'cdr_type' => isset($ivrNode['cdr_type']) ? $ivrNode['cdr_type'] : '',
                        'queues' => isset($ivrNode['queue']) ? $ivrNode['queue'] : 0,
                        'last_call_time' => isset($ivrNode['last_call_time']) ? $ivrNode['last_call_time'] : '',
                        'time_unit' => isset($ivrNode['time_unit']) ? $ivrNode['time_unit'] : 1,
                        'custom_api_url' => isset($ivrNode['custom_api_url']) ? $ivrNode['custom_api_url'] : '',
                        'custom_api_params' => isset($ivrNode['custom_api_params']) ? $ivrNode['custom_api_params'] : '',
                    );
                    if (!isset($parsedArray[$nodeId])) {
                        $parsedArray[$nodeId] = $attr;
                    } else {
                        array_merge($parsedArray[$nodeId], $attr);
                    }
                    //更新父节点的jump字段
                    if (isset($parsedArray[$parentId])) {
                        $parsedArray[$parentId]['jump'] = $nodeId;
                    } else {
                        $parsedArray[$parentId] = array(
                            'jump' => $nodeId,
                        );
                    }
                    break;
                case NodesType::NODE_TYPE_CALL_MEMORY_CHILDREN://来电记忆接口子节点
                    $attr = array(
                        'name' => isset($ivrNode['name']) ? $ivrNode['name'] : '',
                        'id' => $nodeId,
                        'parentId' => $parentId,
                        'type' => $nodeType,
                    );
                    //是否设置了本身节点
                    if (!isset($parsedArray[$nodeId])) {
                        $parsedArray[$nodeId] = $attr;
                    } else {
                        array_merge($parsedArray[$nodeId], $attr);
                    }
                    //设置父节点中子节点的信息
                    $condition = isset($ivrNode['condition']) ? $ivrNode['condition'] : '';
                    if (!isset($parsedArray[$parentId])) {
                        $parsedArray[$parentId] = array(
                            'children' => array($condition => $nodeId),
                        );
                    } else {
                        if (isset($parsedArray[$parentId]['children'])) {
                            $parsedArray[$parentId]['children'][$condition] = $nodeId;
                        } else {
                            $parsedArray[$parentId]['children'] = array($condition => $nodeId);
                        }
                    }
                    break;
                case NodesType::NODE_TYPE_PHONE://转电话节点
                    $attr = array(
                        'name' => isset($ivrNode['name']) ? $ivrNode['name'] : '',
                        'id' => $nodeId,
                        'parentId' => $parentId,
                        'type' => $nodeType,
                        'phone_line' => isset($ivrNode['phone_line']) ? $ivrNode['phone_line'] : 0,
                        'phone_type' => isset($ivrNode['phone_type']) ? $ivrNode['phone_type'] : 'fixed',
                        'phone_num' => isset($ivrNode['phone_num']) ? $ivrNode['phone_num'] : '',
                        'variable_name' => isset($ivrNode['variable_name']) ? $ivrNode['variable_name'] : '',
                        'caller_type' => isset($ivrNode['caller_type']) ? $ivrNode['caller_type'] : '',
                        'caller_variable_name' => isset($ivrNode['caller_variable_name']) ? $ivrNode['caller_variable_name'] : '',
                        'caller' => isset($ivrNode['caller']) ? $ivrNode['caller'] : '',
                    );
                    if (!isset($parsedArray[$nodeId])) {
                        $parsedArray[$nodeId] = $attr;
                    } else {
                        array_merge($parsedArray[$nodeId], $attr);
                    }
                    //更新父节点的jump字段
                    if (isset($parsedArray[$parentId])) {
                        $parsedArray[$parentId]['jump'] = $nodeId;
                    } else {
                        $parsedArray[$parentId] = array(
                            'jump' => $nodeId,
                        );
                    }
                    break;
                case NodesType::NODE_TYPE_AGENT://转坐席节点
                    $attr = array(
                        'name' => isset($ivrNode['name']) ? $ivrNode['name'] : '',
                        'id' => $nodeId,
                        'parentId' => $parentId,
                        'type' => $nodeType,
                        'transfer_type' => isset($ivrNode['transfer_type']) ? $ivrNode['transfer_type'] : 0,
                        'agent' => isset($ivrNode['agent']) ? $ivrNode['agent'] : '',
                        'variable_name' => isset($ivrNode['variable_name']) ? $ivrNode['variable_name'] : '',
                        'transfer_mode' => isset($ivrNode['transfer_mode']) ? $ivrNode['transfer_mode'] : '',
                    );
                    if (!isset($parsedArray[$nodeId])) {
                        $parsedArray[$nodeId] = $attr;
                    } else {
                        array_merge($parsedArray[$nodeId], $attr);
                    }
                    //更新父节点的jump字段
                    if (isset($parsedArray[$parentId])) {
                        $parsedArray[$parentId]['jump'] = $nodeId;
                    } else {
                        $parsedArray[$parentId] = array(
                            'jump' => $nodeId,
                        );
                    }
                    break;
                case NodesType::NODE_TYPE_JUDGE://判断节点
                    $attr = array(
                        'name' => isset($ivrNode['name']) ? $ivrNode['name'] : '',
                        'id' => $nodeId,
                        'parentId' => $parentId,
                        //'conditions' => isset($ivrNode['conditions']) ? $ivrNode['conditions'] : '',
                        'type' => $nodeType,
                    );
                    if (!isset($parsedArray[$nodeId])) {
                        $parsedArray[$nodeId] = $attr;
                    } else {
                        array_merge($parsedArray[$nodeId], $attr);
                    }
                    //更新父节点的jump字段
                    if (isset($parsedArray[$parentId])) {
                        $parsedArray[$parentId]['jump'] = $nodeId;
                    } else {
                        $parsedArray[$parentId] = array(
                            'jump' => $nodeId,
                        );
                    }
                    break;
                case NodesType::NODE_TYPE_JUDGE_CHILDREN://判断子节点
                    $attr = array(
                        'name' => isset($ivrNode['condition']) ? $ivrNode['condition'] : '',
                        'show_name' => isset($ivrNode['name']) ? $ivrNode['name'] : '',
                        'id' => $nodeId,
                        'parentId' => $parentId,
                        'type' => $nodeType,
                    );
                    //是否设置了本身节点
                    if (!isset($parsedArray[$nodeId])) {
                        $parsedArray[$nodeId] = $attr;
                    } else {
                        array_merge($parsedArray[$nodeId], $attr);
                    }
                    //设置父节点中子节点的信息
                    $condition = isset($ivrNode['condition']) ? $ivrNode['condition'] : '';
                    if ($ivrNode['name'] != 'F') {
                        $parsedArray[$parentId]['conditions'][$condition] = array(
                            'and' => @$ivrNode['and'],
                            'or' => @$ivrNode['or'],
                        );
                    }
                    if (!isset($parsedArray[$parentId])) {
                        $ivrNode['name'] = isset($ivrNode['name']) ? $ivrNode['name'] : '';
                        $parsedArray[$parentId] = array(
                            'children' => array($condition => $nodeId),
                        );
                    } else {
                        if (isset($parsedArray[$parentId]['children'])) {
                            $parsedArray[$parentId]['children'][$condition] = $nodeId;
                        } else {
                            $parsedArray[$parentId]['children'] = array($condition => $nodeId);
                        }
                    }
                    break;
                case NodesType::NODE_TYPE_EXISTS://已存在节点
                    $sourceNode = isset($ivrNode['sourceNode']) ? $ivrNode['sourceNode'] : '';
                    $sourceNode = str_replace('tree_', 'node', $sourceNode);
                    //更新父节点的jump字段
                    if (isset($parsedArray[$parentId])) {
                        $parsedArray[$parentId]['jump'] = $sourceNode;
                    } else {
                        $parsedArray[$parentId] = array(
                            'jump' => $sourceNode,
                        );
                    }
                    break;
                case NodesType::NODE_TYPE_IVR://转ivr;
                    $attr = array(
                        'name' => isset($ivrNode['name']) ? $ivrNode['name'] : '',
                        'id' => $nodeId,
                        'parentId' => $parentId,
                        'type' => $nodeType,
                        'ivr_code' => isset($ivrNode['ivr_node_ivr_code']) ? $ivrNode['ivr_node_ivr_code'] : 0,
                        'ivr_node' => isset($ivrNode['ivr_node_ivr_node']) ? $ivrNode['ivr_node_ivr_node'] : '',
                    );
                    if (!isset($parsedArray[$nodeId])) {
                        $parsedArray[$nodeId] = $attr;
                    } else {
                        array_merge($parsedArray[$nodeId], $attr);
                    }
                    //更新父节点的jump字段
                    if (isset($parsedArray[$parentId])) {
                        $parsedArray[$parentId]['jump'] = $nodeId;
                    } else {
                        $parsedArray[$parentId] = array(
                            'jump' => $nodeId,
                        );
                    }
                    break;
            }
            $parsedArray[$nodeId]['ivr_count'] = isset($ivrNode['ivr_count']) ? $ivrNode['ivr_count'] : false;
            if (isset($ivrNode['ivr_count_name'])) {
                $parsedArray[$nodeId]['ivr_count_name'] = trim($ivrNode['ivr_count_name']);
            } else {
                $parsedArray[$nodeId]['ivr_count_name'] = isset($ivrNode['name']) ? trim($ivrNode['name']) : $ivrNode['name'];
            }

        }

        return $parsedArray;
    }

    /**
     * 新的通知程序
     * @param $ivrId
     * @param $vcc_id
     * @param string $logAction
     * @return bool
     */
    private function sendNoticeMessage($ivrId, $vcc_id, $logAction = 'create')
    {
        if (empty($ivrId)) {
            return false;
        }
        $conn = $this->get('doctrine.dbal.default_connection');
        $logger = $this->container->get('logger');
        //添加更新记录表
        $changelog = array(
            'vcc_id' => $vcc_id,
            'log_type' => 'ivr',
            'log_action' => $logAction,
            'table_id' => $ivrId
        );
        $ret = $conn->insert('cc_cti_change_logs', $changelog);
        $nid = $conn->lastInsertId();
        if ($ret <= 0) {
            $logger->critical(sprintf('Insert value %s to table cc_cti_change_logs failed.', json_encode($changelog)));
            return false;
        }

        $msg = json_encode(array('nid' => intval($nid)));
        try{
            $culrClient = new Client(
                array(
                    'base_uri'=>$this->container->getParameter('sound_distribute_url'),
                    'timeout'=>10
                )
            );
            $response = $culrClient->request('GET', '',  array('query'=>array('text'=>$msg)));
            $res = json_decode($response->getBody(), true);
            if (json_last_error() === JSON_ERROR_NONE && isset($res['ret']) && $res['ret'] == 0) {
                return true;
            } else {
                $logger->critical(sprintf('调用语音分发接口错误,返回【%s】', $response->getBody()));
            }
        } catch (\Exception $e) {
            $logger->critical(sprintf('调用语音分发接口错误【%s】', $e->getMessage()));
        }

        return false;
    }

    /**
     * 添加更新记录表，以及通知分发服务有更新
     *
     * @param int    $ivrId     更新的语音ID
     * @param int    $vccId     企业id
     * @param string $logAction 操作(create,update)
     * @return bool
     */
    public function addToChangelogAndSendNoticeToZmqServer($ivrId, $vccId, $logAction = 'create')
    {
        if (empty($ivrId)) {
            return false;
        }

        $conn = $this->get('doctrine.dbal.default_connection');

        $logger = $this->container->get('logger');
        //添加更新记录表
        $changelog = array(
            'vcc_id' => $vccId,
            'log_type' => 'ivr',
            'log_action' => $logAction,
            'table_id' => $ivrId,
        );
        $ret = $conn->insert('cc_cti_change_logs', $changelog);
        $nid = $conn->lastInsertId();
        if ($ret <= 0) {
            $logger->critical(sprintf('Insert value %s to table cc_cti_change_logs failed.', json_encode($changelog)));

            return false;
        }

        //发送通知
        $zmqServer = $this->container->getParameter('cti_zmq_server');
        $zmqPort = $this->container->getParameter('cti_zmq_port');

        try {
            $context = new \ZMQContext();
            $requester = new \ZMQSocket($context, \ZMQ::SOCKET_REQ);
            $requester->connect("tcp://$zmqServer:$zmqPort");
            $msg = json_encode(array('nid' => intval($nid)));
            $requester->send($msg);
            $logger->info(sprintf('Send the request to the server %s:%s, the msg is %s.', $zmqServer, $zmqPort, $msg));

            $poll = new \ZMQPoll();
            $poll->add($requester, \ZMQ::POLL_IN);
            $readable = $writeable = array();
            $events = $poll->poll($readable, $writeable, 5000);
            $errors = $poll->getLastErrors();

            //存在错误
            if (count($errors) > 0) {
                foreach ($errors as $error) {
                    $logger->critical(sprintf("Error polling object, the error is %s", $error));

                    return false;
                }
            }

            //收到消息
            if ($events > 0) {
                foreach ($readable as $socket) {
                    if ($socket === $requester) {
                        $reply = $requester->recv();
                    }
                }
            } else {
                $logger->error(sprintf(
                    'There is no events from the poll, maybe the server %s:%s is not reachable.',
                    $zmqServer,
                    $zmqPort
                ));

                return false;
            }

            if (empty($reply)) {
                $logger->critical(sprintf('The reply of the request is empty, needs json.'));

                return false;
            }
            $replyArray = json_decode($reply, true);
            $jsonLastError = json_last_error();
            if ($jsonLastError != JSON_ERROR_NONE) {
                $logger->critical(sprintf('Json decode the reply %s failed, the error is %s.', $reply, $jsonLastError));

                return false;
            }

            $ret = isset($replyArray['ret']) ? $replyArray['ret'] : '-1';
            if ($ret === 0) {
                return true;
            } else {
                $logger->critical(sprintf('The ret of the reply %s is not 0, the reply is %s.', $ret, $reply));

                return false;
            }
        } catch (\ZMQPollException $e) {
            $logger->critical(sprintf('Poll failed: %s', $e->getMessage()));

            return false;
        }
    }

    /**
     * 展示IVR统计页面
     * @param Request $request
     * @return Response
     */
    public function getIvrStaAction(Request $request)
    {
        $vccId = $this->get('security.token_storage')->getToken()->getUser()->getVccId();
        //通过vcc_id获取该企业的IVR信息
        $ivrInfo = $this->get('icsoc_data.model.ivr')->getIvrInfoByIdArray($vccId);

        $ivrId = $request->get('ivr_id', 0);
        $startTime = empty($request->get('start_time')) ? date('Y-m-d') : $request->get('start_time');
        $endTime = empty($request->get('end_time')) ? date('Y-m-d') : $request->get('end_time');
        if (empty($ivrId)) {
            $keys = array_keys($ivrInfo);
            $selected = isset($keys[0]) ? $keys[0] : 0;
        } else {
            $selected = $ivrId;
        }

        $options = array(
            'ivr_id' => array('text' => 'The process name', 'type' => 2, 'options' => $ivrInfo, 'selected' => $selected, 'notice' => false),
            'start_time' => array('text' => 'Start time', 'type' => 3, 'value' => $startTime, 'help' => 'Start Time'),
            'end_time' => array('text' => 'End time', 'type' => 3, 'value' => $endTime, 'help' => 'End Time'),
        );

        //获取当前选中的ivr信息头
        $ivrtitle = $this->get('icsoc_data.model.ivr')->getIvrtitlesById($vccId, $selected);

        return $this->render(
            "IcsocIvrBundle:Ivr:ivr_sta.html.twig",
            array(
                'options' => $options,
                'ivrtitle' => $ivrtitle,
            )
        );
    }

    /**
     *从redis中获取ivr数据
     */
    public function getIvrStaFromRedisAction(Request $request)
    {
        $page = $request->get('page', 1);
        $rows = $request->get('rows', 10);
        $fliter = $request->get('param', '');
        $export = $request->get('export', '');
        $fliter = html_entity_decode(urldecode($fliter));
        $vccId = $this->getUser()->getVccId();
        $ivrId = 0;

        $json = json_decode($fliter, true);
        $time = $this->container->get("icsoc_core.common.class")->rolesCanSearchAllReportDatas($json['start_time'], $json['end_time'].' 23:59:59', 'date');
        if ($time == 'no') {
            $vccId = -1;
        }
        $start = strtotime(date('Y-m-d')." 00:00:00");
        $end = strtotime(date('Y-m-d')." 23:59:59");
        if (!empty($fliter)) {
            if (isset($json['ivr_id']) && !empty($json['ivr_id'])) {
                $ivrId = $json['ivr_id'];
            }
            if (isset($json['start_time']) && !empty($json['start_time'])) {
                $startTime = $json['start_time'];
                if (isset($time['startTime'])) {
                    $startTime = $time['startTime'];
                }
                $start  = strtotime($startTime);
            }
            if (isset($json['end_time']) && !empty($json['end_time'])) {
                $endTime = $json['end_time'];
                if (isset($time['endTime'])) {
                    $endTime = $time['endTime'];
                }
                $end = strtotime($endTime);
            }
            $during = ($end-$start) / 86400;
            $limit = ($page-1) * $rows;

            $data = array();
            if ($during >= 0) {
                for ($i = 0;$i < $during;$i++) {
                    $now = date('Y-m-d',$start+24*3600*$i);
                    $redisIvrHashName = sprintf("ivrnodesta-%s-%s-%s", $vccId, $ivrId, $now);
                    $range = $this->get('snc_redis.default')->hgetall($redisIvrHashName);
                    if (!empty($range)) {
                        $range['deal_date'] = $now;
                        $data[] = $range;
                    }
                }
            }

            $count = count($data);
            $totalPages = ceil($count/$rows);
            if ($page > $totalPages) {
                $page = $totalPages;
            }
            $res = array();
            if (!empty($export)) {
                $res = $data;
            } else {
                for ($r = $limit;$r < $rows*$page;$r++) {
                    if ( isset($data[$r])) {
                        $res[] = $data[$r];
                    }

                }
            }
        }

        $ivrInfo = $this->get('icsoc_data.model.ivr')->getIvrInfoByIdArray($vccId);
        $all = array();
        $nodes = $this->get('icsoc_data.model.ivr')->getIvrInfoById($vccId, $ivrId);
        if (!empty($res) && is_array($res)) {
            foreach ($res as $key => $val) {
                $all[$key]['ivr_name'] = empty($ivrInfo[$ivrId]) ? '' : $ivrInfo[$ivrId];
                $all[$key]['deal_date'] = empty($val['deal_date']) ? '' : $val['deal_date'];
                unset($val['deal_date']);
                if (!empty($val)) {
                    foreach ($val as $node => $v) {
                        if (in_array($node, $nodes)) {
                            $all[$key][$node] = empty($v) ? 0 : $v;
                        } else {
                            $all[$key][$node] = 0;
                        }
                    }
                } else {
                    foreach ($nodes as $node) {
                        $all[$key][$node] = 0;
                    }
                }
            }
        }

        $customTitle = $this->get('icsoc_data.model.ivr')->getIvrtitlesById($vccId, $ivrId);
        /** 导出功能 */
        if (!empty($export)) {
            /** @var  $title (导出字段) */
            $title = array('ivr_name' => '流程名称');
            $title = array_merge($title, array('deal_date' => '日期'));
            $title = array_merge($title, $customTitle);
            $translator = $this->get('translator');
            switch ($export) {
                case 'csv':
                    return $this->exportCsv($all, json_encode($title), array(
                        'text' => $translator->trans('Ivr Sta Report'),
                        'href' => $this->generateUrl('icsoc_ivr_sta'),
                    ));
                case 'excel':
                    return $this->exportExcel($all, json_encode($title), array(
                        'text' => $translator->trans('Ivr Sta Report'),
                        'href' => $this->generateUrl('icsoc_ivr_sta'),
                    ));
                default:
                    exit;
            }
        }

        $reponse['rows'] = $all;
        $reponse['page'] = $page;
        $reponse['total'] = $totalPages;
        $reponse['records'] = $count;

        return new JsonResponse($reponse);

    }

    /**
     * 获取IVR统计数据结果
     *
     * @param Request $request
     * @return JsonResponse
     * @throws \Doctrine\ORM\NonUniqueResultException
     */
    public function ivrStaDataAction(Request $request)
    {
        $page = $request->get('page', 1);
        $rows = $request->get('rows', 10);
        $sord = $request->get('sord', 'asc');
        $sidx = $request->get('sidx', 'id');
        $fliter = $request->get('param', '');
        $export = $request->get('export', '');
        $fliter = html_entity_decode(urldecode($fliter));
        $vccId = $this->getUser()->getVccId();
        $ivrId = 0;
        $where = ' AND vcc_id = :vcc_id ';
        $parameter['vcc_id'] = $vccId;

        //查询条件
        if (!empty($fliter)) {
            $json = json_decode($fliter, true);
            if (isset($json['ivr_id']) && !empty($json['ivr_id'])) {
                $where .= " AND ivr_id = :ivr_id";
                $parameter['ivr_id'] = $json['ivr_id'];
                $ivrId = $json['ivr_id'];
            }
            //时间条件
            if (isset($json['start_time']) && !empty($json['start_time'])) {
                $where .= " AND deal_date >= :start_time";
                $parameter['start_time'] = $json['start_time'];
            }
            if (isset($json['end_time']) && !empty($json['end_time'])) {
                $where .= " AND deal_date <= :end_time";
                $parameter['end_time'] = $json['end_time'];
            }
        }
        $conn = $this->get('doctrine.dbal.default_connection');
        $total = $conn->fetchColumn(
            "SELECT count(*) as nums FROM win_ivr_sta WHERE 1 $where",
            $parameter,
            0
        );

        if ($total > 0) {
            $totalPage = ceil($total / $rows);
        } else {
            $totalPage = 1;
        }
        if ($page > $totalPage) {
            $page = $totalPage;
        }
        $start = ($page - 1) * $rows;
        /* $result = $conn->fetchAll(
             "SELECT id,vcc_id,ivr_id,ivr_sta,deal_date
             FROM win_ivr_sta WHERE 1 $where ORDER BY $sidx $sord LIMIT $start,$rows",
             $parameter
         );*/

        if (!empty($export)) {
            $result = $conn->fetchAll(
                "SELECT id,vcc_id,ivr_id,ivr_sta,deal_date
            FROM win_ivr_sta WHERE 1 $where ORDER BY $sidx $sord ",
                $parameter
            );
        } else {
            $result = $conn->fetchAll(
                "SELECT id,vcc_id,ivr_id,ivr_sta,deal_date
            FROM win_ivr_sta WHERE 1 $where ORDER BY $sidx $sord LIMIT $start,$rows",
                $parameter
            );
        }

        $ivrInfo = $this->get('icsoc_data.model.ivr')->getIvrInfoByIdArray($vccId);
        $all = array();
        $nodes = $this->get('icsoc_data.model.ivr')->getIvrInfoById($vccId, $ivrId);
        if (!empty($result) && is_array($result)) {
            foreach ($result as $key => $val) {
                $all[$key]['ivr_name'] = empty($ivrInfo[$val['ivr_id']]) ? '' : $ivrInfo[$val['ivr_id']];
                $all[$key]['deal_date'] = empty($val['deal_date']) ? '' : $val['deal_date'];
                if (!empty($val['ivr_sta'])) {
                    $ivrSta = json_decode($val['ivr_sta'], true);
                    foreach ($ivrSta as $v) {
                        if (in_array($v['id'], $nodes)) {
                            $all[$key][$v['id']] = empty($v['count']) ? 0 : $v['count'];
                        } else {
                            $all[$key][$v['id']] = 0;
                        }
                    }
                } else {
                    //查询当前的呼叫
                    foreach ($nodes as $node) {
                        $all[$key][$node] = 0;
                    }
                }
            }
        }

        $customTitle = $this->get('icsoc_data.model.ivr')->getIvrtitlesById($vccId, $ivrId);
        /** 导出功能 */
        if (!empty($export)) {
            /** @var  $title (导出字段) */
            $title = array('ivr_name' => '流程名称');
            $title = array_merge($title, array('deal_date' => '日期'));
            $title = array_merge($title, $customTitle);
            $translator = $this->get('translator');
            switch ($export) {
                case 'csv':
                    return $this->exportCsv($all, json_encode($title), array(
                        'text' => $translator->trans('Ivr Sta Report'),
                        'href' => $this->generateUrl('icsoc_ivr_sta'),
                    ));
                case 'excel':
                    return $this->exportExcel($all, json_encode($title), array(
                        'text' => $translator->trans('Ivr Sta Report'),
                        'href' => $this->generateUrl('icsoc_ivr_sta'),
                    ));
                default:
                    exit;
            }
        }

        $reponse['rows'] = $all;
        $reponse['page'] = $page;
        $reponse['total'] = $totalPage;
        $reponse['records'] = $total;

        return new JsonResponse($reponse);
    }


    /**
     * 导出Excel
     *
     * @param array  $data
     * @param string $title
     * @param array  $link
     *
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|Response
     */
    public function exportExcel(array $data, $title, array $link)
    {
        set_time_limit(0);
        $translator = $this->get('translator');

        /** 限制导出条数，导出数据量过大禁止导出 */
        if (count($data) > 25000) {
            $param = array(
                'data' => array(
                    'msg_detail' => $translator->trans(
                        'Export export large amount of data in batches, please'
                    ),
                    'type' => 'info',
                ),
            );

            return $this->redirect($this->generateUrl('system_message', $param));
        }

        if (empty($title) || !is_string($title)) {
            $param = array(
                'data' => array(
                    'msg_detail' => $translator->trans(
                        'Title is empty or is not string, the type is %type%',
                        array('%type%' => gettype($title))
                    ),
                    'link' => array($link),
                    'type' => 'danger',
                ),
            );

            return $this->redirect($this->generateUrl('system_message', $param));
        }

        $fields = array();
        $titleArray = json_decode($title, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            $data = array(
                'data' => array(
                    'msg_detail' => $translator->trans(
                        'Parse Json Error: %error%',
                        array('%error%' => json_last_error())
                    ),
                    'link' => array($link),
                    'type' => 'danger',
                ),
            );

            return $this->redirect($this->generateUrl('system_message', $data));
        }

        $datas = array();
        foreach ($data as $k => $v) {
            foreach ($titleArray as $key => $val) {
                if (!isset($v[$key])) {
                    $v[$key] = '';
                }
                $datas[$k][$key] = $v[$key];
            }
        }

        foreach ($titleArray as $item => $itemText) {
            $fields[$item] = array(
                'name' => $translator->trans($itemText),
                'type' => 'string',
            );
        }

        try {
            $source = new ArrayType($datas, $fields);
            $excel = $this->get('icsoc_core.export.excel');
            $excel->export($source);
        } catch (\Exception $e) {
            $data = array(
                'data' => array(
                    'msg_detail' => $translator->trans(
                        'Export Excel Error: %error%',
                        array('%error%' => $e->getMessage())
                    ),
                    'link' => array($link),
                    'type' => 'danger',
                ),
            );

            return $this->redirect($this->generateUrl('system_message', $data));
        }

        return new Response();
    }

    /**
     * 导出CSV
     *
     * @param array  $data
     * @param string $title
     * @param array  $link
     *
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|Response
     */
    public function exportCsv(array $data, $title, array $link)
    {
        set_time_limit(0);
        $translator = $this->get('translator');

        /** 限制导出条数，导出数据量过大禁止导出 */
        if (count($data) > 100000) {
            $param = array(
                'data' => array(
                    'msg_detail' => $translator->trans(
                        'Export export large amount of data in batches, please'
                    ),
                    'type' => 'info',
                ),
            );

            return $this->redirect($this->generateUrl('system_message', $param));
        }

        $translator = $this->get('translator');

        if (empty($title) || !is_string($title)) {
            $param = array(
                'data' => array(
                    'msg_detail' => $translator->trans(
                        'Title is empty or is not string, the type is %type%',
                        array('%type%' => gettype($title))
                    ),
                    'link' => array(
                        $link,
                    ),
                    'type' => 'danger',
                ),
            );

            return $this->redirect($this->generateUrl('system_message', $param));
        }

        $fields = array();
        $titleArray = json_decode($title, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            $data = array(
                'data' => array(
                    'msg_detail' => $translator->trans(
                        'Parse Json Error: %error%',
                        array('%error%' => json_last_error())
                    ),
                    'link' => array(
                        array(
                            $link,
                        ),
                    ),
                    'type' => 'danger',
                ),
            );

            return $this->redirect($this->generateUrl('system_message', $data));
        }

        $datas = array();
        foreach ($data as $k => $v) {
            foreach ($titleArray as $key => $val) {
                if (!isset($v[$key])) {
                    $v[$key] = '';
                }
                $datas[$k][$key] = $v[$key];
            }
        }

        foreach ($titleArray as $item => $itemText) {
            $fields[$item] = array(
                'name' => $translator->trans($itemText),
                'type' => 'string',
            );
        }

        try {
            $source = new ArrayType($datas, $fields);
            $excel = $this->get('icsoc_core.export.csv');
            $excel->export($source);
        } catch (\Exception $e) {
            $data = array(
                'data' => array(
                    'msg_detail' => $translator->trans(
                        'Export Excel Error: %error%',
                        array('%error%' => $e->getMessage())
                    ),
                    'link' => array(
                        array(
                            $link,
                        ),
                    ),
                    'type' => 'danger',
                ),
            );

            return $this->redirect($this->generateUrl('system_message', $data));
        }

        return new Response();
    }

    /**
     * 处理树形节点
     * @param $arr
     * @param $id
     * @param int $lev
     * @return array
     */
    private function handleIvrNode($arr, $id, $lev = 0)
    {
        static $res = array();
        foreach ($arr as $val) {
            if (!isset($val['parentId'])) {
                $val['parentId'] = 'node0';
            }
            if($val['parentId'] == $id && isset($val['id'])) {
                $res[] = array(
                    'node'=>$val['id'],
                    'name'=>str_repeat("--", $lev).$val['name'],
                );
                $this->handleIvrNode($arr, $val['id'], $lev + 1);
            }
        }

        return $res;
    }
}
